package com.menghao.rpc.netty.model;

import com.menghao.rpc.exception.NetException;
import com.menghao.rpc.netty.TcpClient;
import com.menghao.rpc.spring.BeansManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p>Tcp连接封装.<br>
 *
 * @author MarvelCode.
 */
public class TcpConnection {

    private Channel channel;

    private AtomicBoolean close;

    public TcpConnection(String ip, int port) throws InterruptedException {
        this.close = new AtomicBoolean(true);
        TcpClient tcpClient = BeansManager.getInstance().getBeanByType(TcpClient.class);
        ChannelFuture future = tcpClient.connect(ip, port);
        this.channel = future.channel();
        this.close.set(false);
    }

    public TcpConnection(Channel channel) {
        this.channel = channel;
    }

    public boolean isActive() {
        return channel != null && channel.isActive();
    }

    public void close() {
        if (close.compareAndSet(false, true) && channel != null) {
            channel.close();
        }
    }

    public void write(Object object) {
        if (isActive()) {
            channel.writeAndFlush(object);
            //channelFuture.addListener(ChannelFutureListener.CLOSE);
        } else {
            throw new NetException("Netty Channel is not ready");
        }
    }
}
